/* 
 * @Author: ecitlm
 * @Date:   2017-11-28 17:59:30
 * @Last Modified by:   ecitlm
 * @Last Modified time: 2017-11-29 14:47:24
 */
const express = require('express')
const http = require('http')
const cheerio = require("cheerio")
const app = express()
const request = require("request");
const Iconv = require('iconv-lite');
colors = require('colors'); //控制台彩色输出
const connection = require('../untils/sql'); //导入mysq配置文件


colors.setTheme({
    silly: 'rainbow',
    input: 'grey',
    verbose: 'cyan',
    prompt: 'grey',
    info: 'green',
    data: 'grey',
    help: 'cyan',
    warn: 'yellow',
    debug: 'blue',
    error: 'red'
});

//创建一个connection
connection.connect(function(err) {
    if (err) {
        console.log('[query] - :' + err);
        return;
    }
    console.log('数据库链接成功-connection success');
});

function view(req, res) {
    var res = res;
    var req = req;
    var id = req.query.id || 1;


    //先查询数据库是否有该数据
    var sql = "SELECT  list FROM photo_detail WHERE (id =" + id + ")";
    connection.query(sql, function(err, rows, fields) {
        console.log("===================================".green)
        console.log(sql.green); //输出sql语句
        console.log("===================================".green)
        if (err) {
            console.log('[query] - :' + err);
            return;
        } else {
            console.log(rows[0]);
            if (rows[0]) {
                console.log("========select data  from database 数据库中的数据=====================".verbose)
                res.send({
                    msg: "success",
                    data: JSON.parse(rows[0].list),
                    code: 1
                })
            } else {
                console.log("===============else splider data form curl===================\n".verbose);
                requestApi(res, id);
                /* for (var i = 0; i < 10; i++) {
                    requestApi(res, i);
                    setTimeout(function() {}, 100)
                }
                */
            }
            //console.log(fields); //返回数据库的基本信息、表字段数据长度等
        }
    });
    return false;
}

/**
 * 插入数据库
 * @param {*} links 
 * @param {*} id 
 */
function insert(links, id) {
    var sql = "INSERT INTO photo_detail (`list`, `id`, `title`, `tag`) VALUES ('" + JSON.stringify(links) + "'," + id + ",'" + title + "','" + tag + "')";
    connection.query(sql, function(err, rows, fields) {
        console.log("===================================".green)
        console.log(sql.green); //输出sql语句
        console.log("===================================".green)
        if (err) {
            console.log('[query] - :' + err);
            return;
        }
        console.log(`-----------------数据写入成功-success->>>>id:${id}------------------`);

    });
}

/**
 * 网络请求
 * @param {*} res 
 */
function requestApi(res, id) {
    var url = `http://www.meizitu.com/a/${id}.html`;
    request({
        url: url,
        encoding: null
    }, function(error, response, body) {
        var links = [];
        if (response && response.statusCode == 200) {
            var body = Iconv.decode(body, 'gb2312');
            $ = cheerio.load(body);
            title = $(".metaRight h2").text();
            tag = $(".metaRight p").text().split("Tags:")[1]
            $('#picture p img').each(function() {
                links.push($(this).attr('src'));
            });
            console.log(links);
            res.send({
                msg: "success",
                data: links,
                code: 1
            });
            console.log('\n-----------------开始写入数据库-start>>>>id:' + id + '------------------');
            insert(links, id, title, tag);

        } else {
            res.send({
                msg: "网络好像有，点问题",
                data: "",
                code: 0
            })
        }
    });
}

app.get('/', function(req, res) {
    view(req, res)
});

module.exports = app;